package com.htjx.mall.services;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

import com.htjx.mall.commons.mappers.UserMapper;
import com.htjx.mall.commons.models.User;
import com.htjx.mall.commons.utils.page.Page;
import com.htjx.mall.controllers.vo.UserQuery;

@Service
public class UserService {
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private SequenceManager sequenceManager;
	@Autowired
	private TransactionTemplate transactionTemplate;
	
	public void updateOne(final User user) {
		transactionTemplate.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {
				userMapper.updateOne(user);
			}
		});
	}
	
	/**
	 * 检测唯一属性
	 */
	public boolean checkUniqueByProperty(String propertyName, String propertyValue) {
		return !userMapper.selectByProperty(propertyName, propertyValue).isEmpty();
	}
	
	public User findUniqueBy(String propertyName, String propertyValue) {
		List<User> list = userMapper.selectByProperty(propertyName, propertyValue);
		if (list.isEmpty()) {
			return null;
		}
		if (list.size() == 1) {
			return list.get(0);
		}
		throw new RuntimeException("there are too many rows, actual " + list.size());
	}
	
	public Page<User> page(UserQuery userQuery, Page<User> page) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("offset", page.getFirst() - 1);
		params.put("size", page.getPageSize());
		params.put("userQuery", userQuery);
		List<User> result = userMapper.page(params);
		page.setResult(result);
		if (page.isAutoCount()) {
			int totalCount = userMapper.pageCount(params);
			page.setTotalCount(totalCount);
		}
		
		return page;
	}
}
